﻿using Consul;
using Dralee.ConsulRegister.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;

namespace Dralee.ConsulRegister
{
    public static class ConsulBuilderExtensions
    {
        // 服务注册
        //public static IHostBuilder RegisterConsul(this IHostBuilder app, IApplicationLifetime lifetime, ConsulService consulService, HealthService healthService)
        //{
        //    var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{consulService.IP}:{consulService.Port}"));// 请求注册的consul地址
        //    var httpCheck = new AgentServiceCheck()
        //    {
        //        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), // 服务启动多久后注册
        //        Interval = TimeSpan.FromSeconds(10), // 健康检查时间间隔，心跳间隔
        //        HTTP = $"http://{healthService.Ip}:{healthService.Port}/api/health", // 健康检查地址
        //        Timeout = TimeSpan.FromSeconds(5)
        //    };
        //    // Register service with consul
        //    var registration = new AgentServiceRegistration
        //    {
        //        Checks = new[] { httpCheck },
        //        ID = healthService.Name + "_" + healthService.Port,
        //        Name = healthService.Name,
        //        Address = healthService.Ip,
        //        Port = healthService.Port,
        //        Tags = new[] { $"urlprefix-/{healthService.Name}" } // 添加urlprefix-/serviceName 格式tag标签，以便Fabio识别
        //    };
        //    consulClient.Agent.ServiceRegister(registration).Wait(); // 服务注册时注册，内部实现其实就是使用consul api进行注册 httpClient发起
        //    lifetime.ApplicationStopping.Register(() =>
        //    {
        //        consulClient.Agent.ServiceDeregister(registration.ID).Wait(); // 服务停止时取消注册
        //    });
        //    return app;
        //}
    }
}
